package com.supermap.extend.trafficanalyst;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.supermap.data.*;

import java.util.ArrayList;
import java.util.Collections;

public class Tool {
    public static Point2Ds jsonArrayToPoints(JSONArray jsonArray){

        Point2Ds point2Ds = new Point2Ds();

        for (int i = 0; i < jsonArray.size() ; i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            double x = jsonObject.getDouble("x");
            double y = jsonObject.getDouble("y");
            point2Ds.add(new Point2D(x,y));
        }

        return point2Ds;
    }

    public static JSONArray geoLineToJsonArray(GeoLine geoLine){

        JSONArray jsonArrayResult = new JSONArray();

        if( !geoLine.isEmpty() ){
            for ( int i = 0 ; i < geoLine.getPartCount() ; i++){
                JSONArray jsonArray = new JSONArray();
                Point2D[] point2DS = geoLine.getPart(i).toArray();
                for ( Point2D point2D : point2DS ){
                    JSONObject jsonObject  = new JSONObject();
                    jsonObject.put("x",point2D.getX());
                    jsonObject.put("y",point2D.getY());
                    jsonArray.add(jsonObject);
                }
                jsonArrayResult.add(jsonArray);
            }

            return jsonArrayResult;
        }else {
            return null;
        }
    }

    public static GeoPoint jsonToGeoPoint(JSONObject jsonObject){
        double x = jsonObject.getDouble("x");
        double y = jsonObject.getDouble("y");
        return new GeoPoint(x,y);
    }

    public static Point2Ds geoLineToPoint2Ds(GeoLine geoLine){
        Point2Ds resultPoint2Ds = new Point2Ds();
        for ( int i = 0; i < geoLine.getPartCount(); i++ ){
            Point2D[] point2DS = geoLine.getPart(i).toArray();
            resultPoint2Ds.addRange(point2DS);
        }
        return resultPoint2Ds;
    }

    public static ArrayList<String> stringsToArrayList(String[] strings){
        ArrayList<String> result = new ArrayList<>();
        if (strings != null) {
            Collections.addAll(result, strings);
        }
        return result;
    }

    public static GeoRegion jsonArrayToGeoRegion(JSONArray jsonArray){

        Point2Ds point2Ds = new Point2Ds();

        for (int i = 0; i < jsonArray.size() ; i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            double x = jsonObject.getDouble("x");
            double y = jsonObject.getDouble("y");
            point2Ds.add(new Point2D(x,y));
        }
        GeoRegion geoRegion = new GeoRegion(point2Ds);
        return geoRegion;
    }
}
